package com.administrator.customviewtest.view.scrollview;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.nfc.Tag;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.ScrollView;
import android.widget.Scroller;

/**
 * Created by Administrator on 2017/6/5.
 */

public class MyScrollView extends ScrollView {
    private static final String TAG = "MyScrollView";
    private int currentY;
    private float lastY;
    private float moveY;
    ValueAnimator animator = new ValueAnimator();




    public MyScrollView(Context context) {
        super(context);
    }

    public MyScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        currentY = (int) ev.getRawY();
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_MOVE:
                moveY =  currentY - lastY;
                if (moveY > 0) {
                    if (getScrollY() == 0) {

                        setTranslationY(getTranslationY()+moveY);
//                        MarginLayoutParams marginLayoutParams = (MarginLayoutParams) getLayoutParams();
//                        marginLayoutParams.topMargin += moveY;
//                        requestLayout();

                    }

                } else {
                    MarginLayoutParams marginLayoutParams = (MarginLayoutParams) getLayoutParams();

                    if(getTranslationY()+moveY>=0){
                        setTranslationY(getTranslationY()+moveY);
//                        marginLayoutParams.topMargin += moveY;
//                        requestLayout();
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
                final MarginLayoutParams marginLayoutParams = (MarginLayoutParams) getLayoutParams();
                animator = ValueAnimator.ofFloat(getTranslationY(),0);
                animator.setDuration(300);
                animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    @Override
                    public void onAnimationUpdate(ValueAnimator valueAnimator) {
                        MyScrollView.this.setTranslationY((Float) valueAnimator.getAnimatedValue());
                        requestLayout();
                    }
                });
                animator.start();

                break;
        }

        lastY = currentY;

        return super.onTouchEvent(ev);
    }
}
